document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('profile');
  
  // Load user data
  loadUserData();
  
  // Initialize tabs
  initTabs();
  
  // Initialize form submission
  initFormSubmission();
  
  // Initialize security settings
  initSecuritySettings();
  
  // Initialize avatar change
  initAvatarChange();
  
  // Initialize logout
  initLogout();
  
  /**
   * Load user data
   */
  function loadUserData() {
    ApiService.get('/api/user/info')
      .then(response => {
        if (response.code === 0 && response.data) {
          const user = response.data;
          
          // Update header info
          document.getElementById('user-name').textContent = user.realName || user.username;
          document.getElementById('user-phone').textContent = maskPhone(user.phone);
          document.getElementById('user-email').textContent = user.email ? maskEmail(user.email) : '未设置';
          document.getElementById('user-create-time').textContent = `注册于 ${Utils.formatDate(user.createTime)}`;
          document.getElementById('user-status').textContent = user.status === 1 ? '正常' : '已禁用';
          
          // Update avatar if exists
          if (user.avatar) {
            const avatarContainer = document.getElementById('avatar-container');
            avatarContainer.innerHTML = `<img src="${user.avatar}" alt="用户头像">`;
          }
          
          // Update form fields
          document.getElementById('username').value = user.username;
          document.getElementById('phone').value = user.phone;
          document.getElementById('real-name').value = user.realName || '';
          document.getElementById('id-card').value = user.idCard || '';
          document.getElementById('email').value = user.email || '';
          
          // Update security settings
          if (user.email) {
            document.getElementById('email-bind-status').textContent = '已绑定';
            document.getElementById('email-bind-status').className = 'security-status success';
            document.getElementById('bind-email-btn').textContent = '更换';
          }
          
          // Payment password status (assuming it's stored in user info or can be determined)
          const hasPaymentPassword = user.hasPaymentPassword || false;
          if (hasPaymentPassword) {
            document.getElementById('payment-password-status').textContent = '已设置';
            document.getElementById('payment-password-status').className = 'security-status success';
            document.getElementById('set-payment-password-btn').textContent = '修改';
          }
          
          // Save user data to localStorage for quick access
          localStorage.setItem('userInfo', JSON.stringify(user));
          
          // Load login history
          loadLoginHistory();
        }
      })
      .catch(error => {
        console.error('Error loading user info:', error);
        Toast.error('加载用户信息失败');
      });
  }
  
  /**
   * Initialize tabs
   */
  function initTabs() {
    const tabs = document.querySelectorAll('.profile-tab');
    
    tabs.forEach(tab => {
      tab.addEventListener('click', function() {
        const tabId = this.getAttribute('data-tab');
        
        // Update active tab
        tabs.forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        
        // Update active section
        const sections = document.querySelectorAll('.profile-section');
        sections.forEach(section => section.classList.remove('active'));
        document.getElementById(`${tabId}-section`).classList.add('active');
      });
    });
  }
  
  /**
   * Initialize form submission
   */
  function initFormSubmission() {
    const basicInfoForm = document.getElementById('basic-info-form');
    
    basicInfoForm.addEventListener('submit', function(e) {
      e.preventDefault();
      
      // Get form data
      const formData = {
        realName: document.getElementById('real-name').value,
        idCard: document.getElementById('id-card').value,
        email: document.getElementById('email').value
      };
      
      // Validate form data
      if (formData.idCard && !validateIdCard(formData.idCard)) {
        Toast.error('请输入有效的身份证号');
        return;
      }
      
      if (formData.email && !validateEmail(formData.email)) {
        Toast.error('请输入有效的邮箱地址');
        return;
      }
      
      // Submit form
      ApiService.put('/api/user/update', formData)
        .then(response => {
          if (response.code === 0) {
            Toast.success('保存成功');
            loadUserData(); // Reload user data
          } else {
            Toast.error(response.message || '保存失败');
          }
        })
        .catch(error => {
          console.error('Error updating user info:', error);
          Toast.error('保存失败');
        });
    });
  }
  
  /**
   * Initialize security settings
   */
  function initSecuritySettings() {
    // Change password
    document.getElementById('change-password-btn').addEventListener('click', function() {
      document.getElementById('change-password-form').reset();
      document.getElementById('change-password-modal').classList.add('show');
    });
    
    document.getElementById('cancel-password-btn').addEventListener('click', function() {
      document.getElementById('change-password-modal').classList.remove('show');
    });
    
    document.querySelector('#change-password-modal .modal-close').addEventListener('click', function() {
      document.getElementById('change-password-modal').classList.remove('show');
    });
    
    document.getElementById('save-password-btn').addEventListener('click', function() {
      const oldPassword = document.getElementById('old-password').value;
      const newPassword = document.getElementById('new-password').value;
      const confirmPassword = document.getElementById('confirm-password').value;
      
      // Validate
      if (!oldPassword) {
        Toast.error('请输入原密码');
        return;
      }
      
      if (!validatePassword(newPassword)) {
        Toast.error('新密码长度需要在8-20位之间，并且包含字母和数字');
        return;
      }
      
      if (newPassword !== confirmPassword) {
        Toast.error('两次密码输入不一致');
        return;
      }
      
      // Submit
      ApiService.put('/api/user/password', {
        oldPassword: oldPassword,
        newPassword: newPassword,
        confirmPassword: confirmPassword
      })
        .then(response => {
          if (response.code === 0) {
            Toast.success('密码修改成功');
            document.getElementById('change-password-modal').classList.remove('show');
          } else {
            Toast.error(response.message || '密码修改失败');
          }
        })
        .catch(error => {
          console.error('Error changing password:', error);
          Toast.error('密码修改失败');
        });
    });
    
    // Set payment password
    document.getElementById('set-payment-password-btn').addEventListener('click', function() {
      const isModify = this.textContent === '修改';
      document.getElementById('payment-password-title').textContent = isModify ? '修改交易密码' : '设置交易密码';
      document.getElementById('old-payment-password-group').style.display = isModify ? 'block' : 'none';
      document.getElementById('payment-password-form').reset();
      document.getElementById('payment-password-modal').classList.add('show');
    });
    
    document.getElementById('cancel-payment-password-btn').addEventListener('click', function() {
      document.getElementById('payment-password-modal').classList.remove('show');
    });
    
    document.querySelector('#payment-password-modal .modal-close').addEventListener('click', function() {
      document.getElementById('payment-password-modal').classList.remove('show');
    });
    
    document.getElementById('save-payment-password-btn').addEventListener('click', function() {
      const isModify = document.getElementById('payment-password-title').textContent === '修改交易密码';
      const oldPaymentPassword = isModify ? document.getElementById('old-payment-password').value : null;
      const newPaymentPassword = document.getElementById('new-payment-password').value;
      const confirmPaymentPassword = document.getElementById('confirm-payment-password').value;
      
      // Validate
      if (isModify && !oldPaymentPassword) {
        Toast.error('请输入原交易密码');
        return;
      }
      
      if (!validatePaymentPassword(newPaymentPassword)) {
        Toast.error('交易密码必须是6位数字');
        return;
      }
      
      if (newPaymentPassword !== confirmPaymentPassword) {
        Toast.error('两次密码输入不一致');
        return;
      }
      
      // Submit
      const apiEndpoint = isModify ? '/api/user/payment-password/update' : '/api/user/payment-password/set';
      const requestData = isModify 
        ? { oldPassword: oldPaymentPassword, newPassword: newPaymentPassword } 
        : { password: newPaymentPassword };
      
      ApiService.post(apiEndpoint, requestData)
        .then(response => {
          if (response.code === 0) {
            Toast.success(isModify ? '交易密码修改成功' : '交易密码设置成功');
            document.getElementById('payment-password-modal').classList.remove('show');
            
            // Update status
            document.getElementById('payment-password-status').textContent = '已设置';
            document.getElementById('payment-password-status').className = 'security-status success';
            document.getElementById('set-payment-password-btn').textContent = '修改';
          } else {
            Toast.error(response.message || (isModify ? '交易密码修改失败' : '交易密码设置失败'));
          }
        })
        .catch(error => {
          console.error('Error setting payment password:', error);
          Toast.error(isModify ? '交易密码修改失败' : '交易密码设置失败');
        });
    });
    
    // Bind email
    document.getElementById('bind-email-btn').addEventListener('click', function() {
      // Open the basic info tab and focus on email field
      const tabs = document.querySelectorAll('.profile-tab');
      tabs.forEach(t => t.classList.remove('active'));
      document.querySelector('.profile-tab[data-tab="basic-info"]').classList.add('active');
      
      const sections = document.querySelectorAll('.profile-section');
      sections.forEach(section => section.classList.remove('active'));
      document.getElementById('basic-info-section').classList.add('active');
      
      document.getElementById('email').focus();
    });
    
    // Change phone
    document.getElementById('change-phone-btn').addEventListener('click', function() {
      Toast.info('更换手机号请联系客服');
    });
  }
  
  /**
   * Initialize avatar change
   */
  function initAvatarChange() {
    document.getElementById('change-avatar-btn').addEventListener('click', function() {
      document.getElementById('avatar-input').click();
    });
    
    document.getElementById('avatar-input').addEventListener('change', function(e) {
      const file = e.target.files[0];
      
      if (!file) {
        return;
      }
      
      // Validate file type
      const fileType = file.type;
      if (!fileType.startsWith('image/')) {
        Toast.error('请选择图片文件');
        return;
      }
      
      // Validate file size (max 2MB)
      if (file.size > 2 * 1024 * 1024) {
        Toast.error('图片大小不能超过2MB');
        return;
      }
      
      // Create FormData
      const formData = new FormData();
      formData.append('file', file);
      
      // Upload avatar
      ApiService.postForm('/api/user/avatar', formData)
        .then(response => {
          if (response.code === 0 && response.data) {
            const avatarUrl = response.data;
            
            // Update avatar
            const avatarContainer = document.getElementById('avatar-container');
            avatarContainer.innerHTML = `<img src="${avatarUrl}" alt="用户头像">`;
            
            // Update user info in localStorage
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            userInfo.avatar = avatarUrl;
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
            
            Toast.success('头像上传成功');
          } else {
            Toast.error(response.message || '头像上传失败');
          }
        })
        .catch(error => {
          console.error('Error uploading avatar:', error);
          Toast.error('头像上传失败');
        });
    });
  }
  
  /**
   * Initialize logout
   */
  function initLogout() {
    document.getElementById('logout-btn').addEventListener('click', function() {
      if (confirm('确定要退出登录吗？')) {
        ApiService.post('/api/user/logout')
          .then(response => {
            // Clear localStorage
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            
            // Redirect to login page
            window.location.href = '/login.html';
          })
          .catch(error => {
            console.error('Error logging out:', error);
            
            // Force logout even if API fails
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = '/login.html';
          });
      }
    });
  }
  
  /**
   * Load login history
   */
  function loadLoginHistory() {
    const activityListElement = document.getElementById('activity-list');
    
    ApiService.get('/api/user/login-history', { page: 1, size: 10 })
      .then(response => {
        if (response.code === 0 && response.data) {
          const loginHistory = response.data.list || [];
          
          if (loginHistory.length === 0) {
            activityListElement.innerHTML = `
              <div class="empty-state">
                <p>暂无登录记录</p>
              </div>
            `;
            return;
          }
          
          let html = '';
          loginHistory.forEach(record => {
            html += `
              <div class="activity-item">
                <div class="activity-icon login">
                  <i class="fas fa-sign-in-alt"></i>
                </div>
                <div class="activity-content">
                  <div class="activity-title">登录成功</div>
                  <div class="activity-meta">
                    <div class="activity-time">${Utils.formatDate(record.loginTime, true)}</div>
                    <div class="activity-location">
                      <i class="fas fa-map-marker-alt"></i>
                      ${record.ip} ${record.location || '未知位置'}
                    </div>
                  </div>
                </div>
              </div>
            `;
          });
          
          activityListElement.innerHTML = html;
        } else {
          activityListElement.innerHTML = `
            <div class="empty-state">
              <p>加载登录记录失败</p>
            </div>
          `;
        }
      })
      .catch(error => {
        console.error('Error loading login history:', error);
        activityListElement.innerHTML = `
          <div class="empty-state">
            <p>加载登录记录失败</p>
          </div>
        `;
      });
  }
  
  /**
   * Utility functions
   */
  
  // Mask phone number
  function maskPhone(phone) {
    if (!phone) return '';
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
  
  // Mask email
  function maskEmail(email) {
    if (!email) return '';
    const parts = email.split('@');
    if (parts.length !== 2) return email;
    
    let username = parts[0];
    const domain = parts[1];
    
    if (username.length <= 2) {
      username = username.charAt(0) + '*';
    } else {
      username = username.charAt(0) + '*'.repeat(username.length - 2) + username.charAt(username.length - 1);
    }
    
    return `${username}@${domain}`;
  }
  
  // Validate ID card
  function validateIdCard(idCard) {
    // Simple validation: 15 or 18 digits
    return /^\d{15}$|^\d{17}[\dXx]$/.test(idCard);
  }
  
  // Validate email
  function validateEmail(email) {
    return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email);
  }
  
  // Validate password
  function validatePassword(password) {
    // At least 8 characters, max 20 characters, must contain letters and numbers
    return /^(?=.*[A-Za-z])(?=.*\d)[\w\d!@#$%^&*()]{8,20}$/.test(password);
  }
  
  // Validate payment password
  function validatePaymentPassword(password) {
    // 6 digits
    return /^\d{6}$/.test(password);
  }
});
